using System.Collections.Generic;
using System.Reflection;

namespace EGEngine
{
    public static class EventModule
    {
        private static readonly Dictionary<int, List<EventObject>> EventObjectDic = new();

        public static void BroadCast(int eventId, params object[] data)
        {
            if (EventObjectDic.TryGetValue(eventId, out var value))
            {
                foreach (var eventObject in value)
                {
                    eventObject.method.Invoke(eventObject.obj, data);
                }
            }
        }

        public static void Register(object obj)
        {
            var methods = obj.GetType().GetMethods();
            foreach (var method in methods)
            {
                var attribute = method.GetCustomAttribute<EventMethodAttribute>();
                if (attribute != null)
                {
                    if (!EventObjectDic.ContainsKey(attribute.eventId))
                    {
                        EventObjectDic[attribute.eventId] = new List<EventObject>();
                    }

                    EventObjectDic[attribute.eventId].Add(new EventObject()
                    {
                        method = method,
                        obj = obj
                    });
                }
            }
        }

        public static void Unregister(object obj)
        {
            List<int> keys = new List<int>();
            foreach (var kv in EventObjectDic)
            {
                for (int i = 0; i < kv.Value.Count; i++)
                {
                    var eventObj = kv.Value[i];
                    if (eventObj.obj == obj)
                    {
                        kv.Value.RemoveAt(i);
                        if (kv.Value.Count == 0)
                        {
                            keys.Add(kv.Key);
                        }

                        i--;
                    }
                }
            }

            foreach (var key in keys)
            {
                EventObjectDic.Remove(key);
            }
        }
    }
}